using System;
using System.Collections.Generic;
using System.Data;
using System.Text;


namespace ClientTools.Library.Logging
{
    public class LogManager: BaseManager 
    {
        public LogManager(string connectionString): base(connectionString) {
        }
        
        public LogInfoCollection GetLogInfos()
        {
            System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand("SELECT logHeader, Count(*) ANZ FROM umbracoLog GROUP BY logHeader ORDER BY logHeader", this.GetConnection());
            System.Data.SqlClient.SqlDataReader datareader = command.ExecuteReader();

            LogInfoCollection returnValue = new LogInfoCollection();
            while (datareader.Read())
            {
                LogInfo li = new LogInfo();
                li.LogHeader = (string)datareader["logHeader"];
                li.Count = (int)datareader["ANZ"];
                returnValue.Add(li);
            }
            return returnValue;
        }

        public int DeleteLogsByDate(DateTime dat)
        {
            System.Data.SqlClient.SqlCommand com = new System.Data.SqlClient.SqlCommand(string.Concat("DELETE FROM umbracoLog WHERE Datestamp < CONVERT(datetime, '", dat.ToString("yyyy-MM-dd"), "', 102)"), this.GetConnection());
            return com.ExecuteNonQuery();
        }

        public int DeleteLogsByHeader(string header)
        {
            System.Data.SqlClient.SqlCommand com = new System.Data.SqlClient.SqlCommand(string.Concat("DELETE FROM umbracoLog WHERE logHeader = '", header, "'"), this.GetConnection());
            return com.ExecuteNonQuery();
        }

        public int DeleteLogsByIDs(int[] logIds)
        {
            if (logIds.Length == 0) 
            {
                return 0;
            }
            else
            {
                string s = "";
                if (logIds.Length == 1)
                {
                    s = logIds[0].ToString();
                }
                else
                {
                    foreach (int i in logIds)
                    {
                        s += "," + i.ToString();
                    }
                    s = s.Substring(1);
                }
                System.Data.SqlClient.SqlCommand com = new System.Data.SqlClient.SqlCommand(string.Concat("DELETE FROM umbracoLog WHERE id IN (", s, ")"), this.GetConnection());
                return com.ExecuteNonQuery();
            }
        }

        public LogCollection GetLogs(System.Nullable<DateTime> dateStart, System.Nullable<DateTime> dateEnd, string logHeader, System.Nullable<int> userId, System.Nullable<int> nodeId, System.Nullable<int> maxRows, string comment)
        {
            System.Data.SqlClient.SqlCommand c = new System.Data.SqlClient.SqlCommand();
            c.Connection = this.GetConnection();
            System.Data.SqlClient.SqlParameter p;
            string sel = "SELECT TOP (" + maxRows.ToString() + ") id, userId, NodeId, Datestamp, logHeader, logComment FROM umbracoLog ";
            string where = "";

            if (logHeader != null && logHeader.Trim() != "")
            {
                where = string.Concat(where, " AND logHeader = @logHeader");
                p = c.Parameters.Add("@logHeader", System.Data.SqlDbType.VarChar);
                p.Value = logHeader;
            }

            if (userId.HasValue)
            {
                where = string.Concat(where, " AND userid = @userid");
                p = c.Parameters.Add("@userid", SqlDbType.Int);
                p.Value = userId;
            }

            if (nodeId.HasValue)
            {
                where = string.Concat(where, " AND NodeID = @NodeID");
                p = c.Parameters.Add("@NodeID", SqlDbType.Int);
                p.Value = nodeId;
            }

            if (dateStart.HasValue)
            {
                where = string.Concat(where, " AND Datestamp > @DateStart");
                p = c.Parameters.Add("@DateStart", SqlDbType.DateTime);
                p.Value = dateStart;
            }

            if (dateEnd.HasValue)
            {
                where = string.Concat(where, " AND Datestamp < @DateEnd");
                p = c.Parameters.Add("@DateEnd", SqlDbType.DateTime);
                p.Value = dateEnd;
            }

            if (comment != null && comment.Trim() != "")
            {
                where = string.Concat(where, " AND LogComment LIKE '%" + comment + "%'");
            }

            if (where.Length == 0)
            {
                c.CommandText = string.Concat(sel, " ORDER BY DateStamp DESC");
            }
            else
            {
                c.CommandText = string.Concat(sel, " WHERE ", where.Substring(4), " ORDER BY DateStamp DESC");
            }

            try
            {
                return this.GetLogsFromDatareader(c.ExecuteReader());
            }
            catch (Exception)
            {
                c.CommandText = c.CommandText.Replace("(", "").Replace(")", "");
                return this.GetLogsFromDatareader(c.ExecuteReader());
            }
        }

        private LogCollection GetLogsFromDatareader(System.Data.SqlClient.SqlDataReader datareader)
        {
            LogCollection returnValue = new LogCollection();

            while (datareader.Read())
            {
                Log log = new Log();
                log.ID = datareader.GetInt32(0);
                log.UserId = datareader.GetInt32(1);
                log.NodeId = datareader.GetInt32(2);
                log.DateStamp = datareader.GetDateTime(3);
                log.LogHeader = datareader.GetString(4);
                log.LogComment = datareader.GetString(5);
                returnValue.Add(log);
            }
            return returnValue;
        }
    }
}
